package com.parktech.sun.web.controller.management.report;

import com.parktech.sun.domain.model.Constants;
import com.parktech.sun.domain.model.report.KeyEconomyPropFinishStatus;
import com.parktech.sun.domain.model.report.KeyEconomyPropOutput;
import com.parktech.sun.domain.model.sunhz.Enterprise;
import com.parktech.sun.domain.model.sunhz.EnterpriseCategoryProduct;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.service.report.KeyEconomyPropFinishStatusService;
import com.parktech.sun.domain.service.sunhz.EnterpriseCategoryProductService;
import com.parktech.sun.domain.service.sunhz.EnterpriseService;
import com.parktech.sun.domain.service.sunhz.KeyEconomyPropOutputService;
import com.parktech.sun.utils.AjaxUtil;
import com.parktech.sun.web.controller.management.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: guo
 * Date: 11-1-16
 * Time: 下午8:51
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/management/report")
public class KeyEconomyPropFinishStatusController extends BaseController {
    @Autowired
    private KeyEconomyPropFinishStatusService keyEconomyPropFinishStatusService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private EnterpriseCategoryProductService enterpriseCategoryProductService;
    @Autowired
    private KeyEconomyPropOutputService keyEconomyPropOutputService;


    private final String redirectListURL = "redirect:listKeyEconomyPropFinishStatuses";

    @RequestMapping(value = "/listKeyEconomyPropFinishStatuses", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView listKeyEconomyPropFinishStatuses(HttpServletRequest request) {
        Integer currentPageNo = request.getParameter("pageNo") != null ? Integer.parseInt(request.getParameter("pageNo").trim()) : 1;
        ModelAndView modelAndView = new ModelAndView("management/report/keyEconomyPropFinishStatusList");

        List fieldColumns = new ArrayList();
        List searchValues = new ArrayList();
        if (request.getParameter("searchKeyName") != null) {
            fieldColumns.add("name");
            searchValues.add(request.getParameter("searchKeyName"));
        }
        Page<KeyEconomyPropFinishStatus> returnPage = new Page<KeyEconomyPropFinishStatus>(Constants.PAGINATION_PAGE_SIZE, currentPageNo);
        returnPage.setTotalCount(keyEconomyPropFinishStatusService.getTotalSizeWithSimilarCondition(KeyEconomyPropFinishStatus.class, fieldColumns, searchValues));
        returnPage.setResult(keyEconomyPropFinishStatusService.getPaginationObjectsWithSimilarCondition(KeyEconomyPropFinishStatus.class, currentPageNo, Constants.PAGINATION_PAGE_SIZE, fieldColumns, searchValues, null, null));

        return modelAndView.addObject(returnPage);
    }


    //    @ModelAttribute      @RequestParam
    @RequestMapping(value = "/manageKeyEconomyPropFinishStatus", method = RequestMethod.GET)
    public ModelAndView manageKeyEconomyPropFinishStatus(Model model, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("management/report/keyEconomyPropFinishStatusManage");
        Long keyEconomyPropFinishStatusID = request.getParameter("keyEconomyPropFinishStatusID") != null ? Long.parseLong(request.getParameter("keyEconomyPropFinishStatusID").trim()) : null;
        List<Enterprise> enterpriseList = enterpriseService.getPaginationObjectsWithSimilarCondition(Enterprise.class, 1, 6666, null, null, null, null);

        if (keyEconomyPropFinishStatusID == null)     // request to add the new contact keyEconomyPropFinishStatus object
        {
            model.addAttribute(new KeyEconomyPropFinishStatus());
        } else       // request to update the certain keyEconomyPropFinishStatus object
        {
            KeyEconomyPropFinishStatus keyEconomyPropFinishStatus = keyEconomyPropFinishStatusService.getBeanByID(keyEconomyPropFinishStatusID);
            model.addAttribute(keyEconomyPropFinishStatus);
        }
        return modelAndView.addObject(model).addObject("enterpriseList", enterpriseList);
    }

    @RequestMapping(value = "/saveManageKeyEconomyPropFinishStatus", method = RequestMethod.POST)
    public ModelAndView saveManageKeyEconomyPropFinishStatus(@ModelAttribute KeyEconomyPropFinishStatus keyEconomyPropFinishStatus, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("management/report/keyEconomyPropFinishStatusManage");
        Long keyEconomyPropFinishStatusID = keyEconomyPropFinishStatus.getId();
       /// String[] productOutputIDArray = request.getParameterValues("productOutputID");
        String[] productIDArray = request.getParameterValues("productID");
        String[] productOutputArray = request.getParameterValues("productOutput");
        if (keyEconomyPropFinishStatusID ==null)
        {
            if (productIDArray != null && productIDArray.length != 0) {
                for (int i = 0; i < productIDArray.length; i++) {
                    Long productID = Long.valueOf(productIDArray[i]);
                    KeyEconomyPropOutput keyEconomyPropOutput = new KeyEconomyPropOutput();
                    keyEconomyPropOutput.setOutput(productOutputArray[i]);
                    keyEconomyPropOutput.setEnterpriseCategoryProduct(enterpriseCategoryProductService.getBeanByID(productID));
                    keyEconomyPropFinishStatus.addKeyEconomyPropOutput(keyEconomyPropOutput);
                }
                keyEconomyPropFinishStatusService.saveOrUpdateBean(keyEconomyPropFinishStatus);
            }
        } else {
            KeyEconomyPropFinishStatus dbKeyEconomyPropFinishStatus = keyEconomyPropFinishStatusService.getBeanByID(keyEconomyPropFinishStatus.getId());
            keyEconomyPropFinishStatus.setCreateDatetime(dbKeyEconomyPropFinishStatus.getCreateDatetime());
            keyEconomyPropFinishStatus.setCreator(dbKeyEconomyPropFinishStatus.getCreator());
            if (productIDArray != null && productIDArray.length != 0) {
                for (int i = 0; i < productIDArray.length; i++) {
                    Long productID = Long.valueOf(productIDArray[i]);
                    KeyEconomyPropOutput keyEconomyPropOutput = new KeyEconomyPropOutput();
                    keyEconomyPropOutput.setOutput(productOutputArray[i]);
                    keyEconomyPropOutput.setEnterpriseCategoryProduct(enterpriseCategoryProductService.getBeanByID(productID));
                    keyEconomyPropFinishStatus.addKeyEconomyPropOutput(keyEconomyPropOutput);
                }
                keyEconomyPropFinishStatusService.merge(keyEconomyPropFinishStatus);
            }
        }
        List<Enterprise> enterpriseList = enterpriseService.getPaginationObjectsWithSimilarCondition(Enterprise.class, 1, 6666, null, null, null, null);

        if (keyEconomyPropFinishStatusID == null) {
            saveSuccessMessage(request, "创建成功！");
        } else {
            saveSuccessMessage(request, "修改成功！");
        }
        return modelAndView.addObject(keyEconomyPropFinishStatus).addObject("enterpriseList", enterpriseList);
    }

    @RequestMapping(value = "/deleteKeyEconomyPropFinishStatuss", method = RequestMethod.POST)
    public String deleteKeyEconomyPropFinishStatuss(HttpServletRequest request) {
        String[] keyEconomyPropFinishStatusIDArray = request.getParameter("selectedKeyEconomyPropFinishStatusIDArray") == null ? new String[0] : request.getParameter("selectedKeyEconomyPropFinishStatusIDArray").trim().split(",");
        for (String keyEconomyPropFinishStatusID : keyEconomyPropFinishStatusIDArray) {
            keyEconomyPropFinishStatusService.removeBean(Long.valueOf(keyEconomyPropFinishStatusID.trim()));
        }
        return redirectListURL;
    }

    @RequestMapping(value = "ajaxGetProductOutput", method = RequestMethod.GET)
    public void ajaxGetProductOutput(HttpServletRequest request, HttpServletResponse response) {
        String enterpriseID = request.getParameter("enterpriseID");
        String ownerID = request.getParameter("ownerID");
        StringBuilder builder = new StringBuilder();
        if (enterpriseID != null && enterpriseID.trim() != "") {        //
            Enterprise enterprise = enterpriseService.getBeanByID(Long.valueOf(enterpriseID));
            if (ownerID != null && ownerID != "") {     // edit the object
                KeyEconomyPropFinishStatus keyEconomyPropFinishStatus = keyEconomyPropFinishStatusService.getBeanByID(Long.valueOf(ownerID));
                if (enterprise != null && keyEconomyPropFinishStatus != null) {
                    if (keyEconomyPropFinishStatus.getEnterprise().getId().equals(enterprise.getId())) {     // just means the enterprise select in page not changed.
                        builder.append("$('#showProductOutput').html(\"\");");
                        for (KeyEconomyPropOutput keyEconomyPropOutput : keyEconomyPropFinishStatus.getKeyEconomyPropOutputList()) {
                            builder.append("$('#showProductOutput').append(\"<input type='hidden' name='productOutputID' value='" + keyEconomyPropOutput.getId() + "'/><input type='hidden' name='productID' value='" + keyEconomyPropOutput.getEnterpriseCategoryProduct().getId() + "'/>名称：" + keyEconomyPropOutput.getEnterpriseCategoryProduct().getName() + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  产量：<input type='text' name='productOutput' value='" + keyEconomyPropOutput.getOutput() + "'/><br/>\");");
                        }
                    }
                    else            // enterprise select changed
                    {
                        builder.append("$('#showProductOutput').html(\"\");");
                        for (EnterpriseCategoryProduct enterpriseCategoryProduct : enterprise.getProductList()) {
                            builder.append("$('#showProductOutput').append(\"<input type='hidden' name='productID' value='" + enterpriseCategoryProduct.getId() + "'/> 名称：" + enterpriseCategoryProduct.getName() + "  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;产量：<input type='text' name='productOutput'/><br/>\");");
                        }
                    }
                } else {    // bad db
                    builder.append("$('#showProductOutput').html(\"\");");
                }
            } else {    // add the object
                if (enterprise != null) {
                    builder.append("$('#showProductOutput').html(\"\");");
                    for (EnterpriseCategoryProduct enterpriseCategoryProduct : enterprise.getProductList()) {
                        builder.append("$('#showProductOutput').append(\"<input type='hidden' name='productID' value='" + enterpriseCategoryProduct.getId() + "'/> 名称：" + enterpriseCategoryProduct.getName() + "  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;产量：<input type='text' name='productOutput'/><br/>\");");
                    }
                } else {
                    builder.append("$('#showProductOutput').html(\"\");");
                }
            }
        } else // invalid
        {
            builder.append("$('#showProductOutput').html(\"\");");
        }
        try {
            AjaxUtil.outPutJsonStr(response, builder.toString());
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
}
    


